package com.xiaou.es.demo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4J2LoggerFactory;

/**
 * es的简单的批量操作
 * @author xiaou
 * @date 2018年9月14日-下午12:44:21
 */
public class Query1 {
	private TransportClient client;
	private static InternalLogger log =Log4J2LoggerFactory.getInstance(EasyCrud.class);
	
	@SuppressWarnings("resource")
	@Before
	public void before() throws UnknownHostException {
		
		Settings settings = Settings.builder()
				.put("cluster.name", "myes")
				.build();
		client = new PreBuiltTransportClient(settings)
				.addTransportAddress(
						new TransportAddress(InetAddress.getByName("192.168.150.142"), 9300)
						);
	}
	
	@After
	public void after() {
		client.close();
	}
	
	// 使用multget批量查询
	@Test
	public void test1() {
		MultiGetResponse response = client.prepareMultiGet()
											.add("xiaou", "test", "1","2","3","4")
											.get();
		log.info("查询成功");
		for(MultiGetItemResponse item : response) {
			GetResponse gr = item.getResponse();
			if(null != gr && gr.isExists()) {
				System.out.println(gr.getSourceAsString());
			}
		}
	}
	
	// bulk 批量操作
	@Test
	public void test2() throws IOException {
		BulkRequestBuilder requestBuilder = client.prepareBulk();
		requestBuilder.add(client.prepareIndex("xiaou","test", "8")
								 .setSource(XContentFactory.jsonBuilder()
								 .startObject()
								 .field("title","vr")
								 .field("price",25)
								 .endObject()));
		requestBuilder.add(client.prepareIndex("xiaou","test", "9")
								 .setSource(XContentFactory.jsonBuilder()
								 .startObject()
								 .field("title","python")
								 .field("price",66)
								 .endObject()));
		BulkResponse bulkResponse = requestBuilder.get();
		
		log.info(bulkResponse.status().toString());
		if(bulkResponse.hasFailures())
			log.info("存在错误");
		
	}
	
	// 查询批量删除
	@Test
	public void test3()  {
		
		BulkByScrollResponse bulkByScrollResponse = DeleteByQueryAction.INSTANCE
													.newRequestBuilder(client)
													.filter(QueryBuilders.matchQuery("title","python"))
													.source("xiaou")
													.get();
		Long count = bulkByScrollResponse.getDeleted();
		
		log.info("删除了"+count+"条");
		
	}
	// 查询所有的文档
	@Test
	public void test4() {
		
		// 设置查询条件
		MatchAllQueryBuilder query = QueryBuilders.matchAllQuery();
		
		SearchResponse searchResponse = client.prepareSearch("xiaou")
											  .setQuery(query)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
		
		System.out.println("---------------------------------");
		
		for(SearchHit hit : hits) {
			Map<String, Object> map = hit.getSourceAsMap();
			for(Map.Entry<String, Object> entry : map.entrySet()) {
				System.out.println("key:"+entry.getKey()+" |  "+"value:"+entry.getValue());
			}
		}
	}
	// macth查询
	@Test
	public void test5() {
		
		QueryBuilder queryBuilder = QueryBuilders.matchQuery("title","java");
		
		SearchResponse searchResponse = client.prepareSearch("xiaou")
											  .setQuery(queryBuilder)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}
	
	// multiMatch查询
	@Test
	public void test6() {
		QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("rock","first_name","about");
		SearchResponse searchResponse = client.prepareSearch("lib")
											  .setQuery(queryBuilder)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}
	
	// term 查询
	@Test
	public void test7() {
		QueryBuilder queryBuilder = QueryBuilders.termQuery("title", "java");
		SearchResponse searchResponse = client.prepareSearch("xiaou")
											  .setQuery(queryBuilder)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}
	
	// terms 查询
	@Test
	public void test8() {
		QueryBuilder queryBuilder = QueryBuilders.termsQuery("title","java","php");
		SearchResponse searchResponse = client.prepareSearch("xiaou")
											  .setQuery(queryBuilder)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}
	
	// range query
	@Test
	public void test9() {
		QueryBuilder queryBuilder = QueryBuilders.rangeQuery("date")
												.from("1990-01-01")
												.to("2000-01-01")
												.format("yyyy-MM-dd");
		SearchResponse searchResponse = client.prepareSearch("x")
											  .setQuery(queryBuilder)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}
	
	
	@Test
	public void test10() {
		// prefix query
		// QueryBuilder queryBuilder = QueryBuilders.prefixQuery("title", "j");
		// wildcard query 
		// QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("date", "199*");
		// fuzzy query 模糊查询
		// QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("title","jav");
		// type query
		//QueryBuilder queryBuilder = QueryBuilders.typeQuery("test");
		//id query
		QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1","2","3");
		SearchResponse searchResponse = client.prepareSearch("x")
											  .setQuery(queryBuilder)
											  .setSize(3)
											  .get();
		SearchHits hits = searchResponse.getHits();
		for(SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
	}
	
}
